<template>
  <div
    class="UpdateSystemRoleManage-container"
    :class="{'hid': isDialog}"
  >
    <BaseBreadcrumb use-convert>
      <a-card>
        <a-spin
          v-if="!isDialog"
          :spinning="loading.isDetail"
        >
          <div
            class="content-wrapper"
          >
            <title-name title="角色信息">
              <span>角色信息</span>
              <div class="tool-btns">
                <a-button
                  type="primary"
                  @click="handleClose"
                >
                  关闭
                </a-button>
                <a-button
                  v-if="pageType !== 'look'"
                  :loading="loading.isSubmit || (loadingData.isOpr&&loadingData.isBus)"
                  class="ml12"
                  type="primary"
                  @click="handleSubmit"
                >
                  提交
                </a-button>
              </div>
            </title-name>
            <a-form-model
              ref="ruleForm"
              :model="formInfo"
              :rules="rules"
            >
              <a-row :gutter="24">
                <a-col
                  :md="8"
                  :sm="8"
                >
                  <a-form-model-item
                    label="角色名称"
                    :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                    prop="name"
                  >
                    <BaseInput
                      v-model="formInfo.name"
                      :disabled="pageType === 'look'"
                      placeholder="请输入角色名称"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col
                  :md="8"
                  :sm="8"
                >
                  <a-form-model-item
                    label="编码"
                    :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                    prop="code"
                  >
                    <BaseInput
                      v-model="formInfo.code"
                      :disabled="pageType === 'look'"
                      placeholder="请输入编码"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col
                  :md="8"
                  :sm="8"
                >
                  <a-form-model-item
                    label="业务标识"
                    :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                    prop="command"
                  >
                    <a-select
                      v-model="formInfo.command"
                      :disabled="pageType === 'look'"
                      placeholder="请选择业务标识"
                    >
                      <a-select-option
                        v-for="code in businesscodeList"
                        :key="code.command"
                      >
                        {{
                          code.commandName
                        }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col
                  :md="16"
                  :sm="16"
                >
                  <a-form-model-item
                    label="描述"
                    :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                    prop="description"
                  >
                    <BaseTextarea
                      v-model="formInfo.description"
                      :disabled="pageType === 'look'"
                      placeholder="请输入描述"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col
                  :md="8"
                  :sm="8"
                >
                  <a-form-model-item
                    label="状态"
                    :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                    prop="enable"
                  >
                    <a-select
                      v-model="formInfo.enable"
                      :disabled="pageType === 'look'"
                      placeholder="请选择状态"
                    >
                      <a-select-option
                        v-for="status in statusList"
                        :key="status.key"
                      >
                        {{ status.label }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row :gutter="24">
                <a-col
                  :md="24"
                  :sm="24"
                >
                  <a-form-model-item
                    label="关联岗位"
                    :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
                  >
                    <div>
                      <div
                        v-for="(item, index) in formInfo.postList"
                        :key="item.id"
                        class="pos"
                      >
                        {{ item.pname }}
                        <span
                          v-if="pageType !== 'look'"
                          class="close"
                          @click="delPos(index)"
                        >X</span>
                      </div>
                      <a-button
                        v-if="pageType !== 'look'"
                        type="primary"
                        style="display: inline-block"
                        @click="addPost"
                      >
                        添加岗位
                      </a-button>
                    </div>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </div>
        </a-spin>
        <title-name
          v-if="!isDialog"
          title="角色资源"
        />
        <a-button
          v-if="pageType !== 'look'"
          type="primary"
          @click="copyAuth"
        >
          复制权限
        </a-button>
        <a-tabs
          :active-key="activeKey"
          @tabClick="handleTabClick"
        >
          <a-tab-pane
            v-for="item in tabsList"
            :key="item.key"
            :tab="item.label"
          />
        </a-tabs>
        <div
          v-show="activeKey == 'roleInfo'"
          class="content-wrapper"
        >
          <!--          <AuthTable-->
          <!--            ref="authTable"-->
          <!--            :selected-initial="userId ? true: false"-->
          <!--            :selected-keys="roleResourceKeys"-->
          <!--            :disabled="pageType === 'look'"-->
          <!--            :userId="userId"-->
          <!--            tab-type="1"-->
          <!--            @loadFinish="loadFinish"-->
          <!--          />-->
          <RoleTree
            ref="authTable"
            :selected-initial="orgin ? true: false"
            :selected-row-keys="roleResourceKeys"
            :disabled="pageType === 'look'"
            :user-id="userId"
            :roleId="id"
            tab-type="1"
            @loadFinish="loadFinish"
          />
        </div>
        <div
          v-show="activeKey == 'roleResource'"
          class="content-wrapper"
        >
          <div style="display: flex; align-items: center;height: 50px">
            <div>默认权限：</div>
            <div style="height: 28px;line-height: 28px;background: #f2f2f2;padding: 0 10px;margin-right: 10px;width: 200px">
              所有业务菜单
            </div>
          </div>
          <!--          <AuthTable-->
          <!--            ref="authTableBuss"-->
          <!--            :selected-initial="userId ? true: false"-->
          <!--            :selected-keys="roleResourceKeys2"-->
          <!--            :disabled="pageType === 'look'"-->
          <!--            tab-type="2"-->
          <!--            :userId="userId"-->
          <!--            @loadFinish="loadFinish"-->
          <!--          />-->
          <RoleTree
            ref="authTableBuss"
            :selected-initial="orgin ? true: false"
            :selected-row-keys="roleResourceKeys2"
            :disabled="pageType === 'look'"
            tab-type="2"
            :user-id="userId"
            :roleId="id"
            :isCopy="isCopy"
            @loadFinish="loadFinish"
          />
        </div>
        <div
          v-show="activeKey=== 'roleog'"
          class="content-wrapper"
        >
          <Organization
            :select-org-list="selectOrgList"
            :default-num="defaultNum"
            @setUnitList="setUnitList"
            @setDefalt="setDefalt"
            :orgin="orgin"
          />
        </div>
      </a-card>
    </BaseBreadcrumb>
    <Post
      ref="post"
      :select-post="selectPost"
      @setPost="setPost"
    />
    <roleList
      ref="roleListRef"
      @cppyFinish="cppyFinish"
    />
  </div>
</template>

<script>
import { getRoleResource } from '@/api/system/roleManage.js'
import { getPointDomains, addRole, getRoleManageDetailNew, getOrgList } from '@/api/system/system.js'
import { getBusinessCode } from '@/api/system/menuAndAuth.js'
// import AuthTable from './AuthTable'
import Organization from './organization/index'
import Post from './post/index'
import roleList from './roleList/index'
import RoleTree from './AuthTable/roleAuthTreeNew'

const tabsList = [
  {
    label: '业务操作权限',
    key: 'roleInfo',
  },
  {
    label: '业务查询（业务）',
    key: 'roleResource',
  },
  {
    label: '业务查询（组织）',
    key: 'roleog',
  },
]
const statusList = [
  {
    key: 1,
    label: '可用',
  },
  {
    key: 0,
    label: '不可用',
  },
]
export default {
  name: 'UpdateSystemRoleManage',
  components: {
    // AuthTable,
    Organization,
    Post,
    roleList,
    RoleTree
  },
  props: {
    id: {
      type: String,
      default: ''
    },
    userId: {
      type: String,
      default: ''
    },
    isDialog: {
      type: Boolean,
      default: false
    },
    look: {
      type: String,
      default: ""
    },
    orgin: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      domainList: [],
      roleResourceList: [],
      cacheRoleResourceList: [],
      roleResourceList2: [],
      cacheRoleResourceList2: [],
      businesscodeList: [],
      cacheRoleResourceKeys: [],
      cacheRoleResourceKeys2: [],
      tabsList,
      statusList,
      activeKey: tabsList[0].key,
      loading: {
        isDetail: false,
        isSubmit: false,
        isNext: false,
      },
      loadingData: {
        isOpr: true,
        isBus: true
      },
      formInfo: {
        postList: []
      },
      rules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        command: [{ required: true, message: '请选择业务标识', trigger: 'change' }],
        enable: [{ required: true, message: '请选择状态', trigger: 'change' }],
      },
      unitList: [],
      isExtend: 1,
      selectPost: [],
      selectOrgList: [],
      roleId: '',
      isCopy: false,
      defaultNum: 1
    }
  },
  computed: {
    pageType() {
      return this.look || this.$route.query.pageType || 'add'
    },
    roleResourceKeys() {
      return this.roleResourceList.map((item) => item.resId)
    },
    roleResourceKeys2() {
      return this.roleResourceList2.map((item) => item.resId)
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.getBusinessCodeReq()
      if(this.isDialog && !this.userId) {
        this.roleId =  this.id || this.userId
        this.getRoleDetailReq(this.roleId)
      } else if(this.$route.query.id && !this.userId) {
          this.roleId = this.$route.query.id || this.id
          this.getRoleDetailReq(this.roleId)
        }

      if(this.userId) {
        this.getOrgList()
      }
      // todo 单独查询组织回显
      this.getPointDomainsReq()
    },
    getOrgList() {
      //5e3a42971f9a4eb1ad74791d9dd7c4ed
      getOrgList({id: this.userId}).then(res=>{
        const selectOrgList = []
        res.data.roleOrgList && res.data.roleOrgList.forEach(item => {
          const obj = {
            id: item.orgId,
            pName: item.orgName,
            name: item.orgName
          }
          selectOrgList.push(obj)
        })
        this.selectOrgList = selectOrgList;
        this.unitList = selectOrgList;
        this.defaultNum = res.data.isExtend == 1 ? 1 : 2
      })
    },
    loadFinish(type) {
      if(type == 1) {
        this.loadingData.isOpr = false
      } else {
        this.loadingData.isBus = false
      }

      this.$emit('loadFinish',  this.loadingData)
    },
    cppyFinish(id) {
      this.isCopy = true
      // this.getRoleResourceReq(id)
      this.getRoleDetailReq(id)
    },
    copyAuth() {
      this.$refs.roleListRef.open()
    },
    delPos(i) {
      this.formInfo.postList.splice(i, 1)
      this.selectPost = this.formInfo.postList
    },
    setDefalt(val) {
      this.isExtend = val
    },
    setUnitList(val) {
      this.unitList = val;
    },
    setPost(val) {
      this.formInfo.postList = val;
      // const arr = []
      // this.formInfo.postList.forEach(item=>{
      //   const obj = {
      //     id: item.orgId,
      //     pName: item.orgName,
      //     name: item.orgName
      //   }
      //   arr.push(obj)
      // })

      this.selectPost = this.formInfo.postList;
      this.$refs.post.close()
    },
    addPost() {
      this.$refs.post.open()
    },
    /**
     * 获取单点域(新增时需要传)
     */
    async getPointDomainsReq() {
      try {
        const res = await getPointDomains()
        this.domainList = res.data || []
      } catch(e) {
        console.error(e)
      }
    },
    async getRoleResourceReq(id) {
      try {
        const params = {
          roleId: id,
          resType: '',
        }
        const res = await getRoleResource(params)
        const arr1 = [], arr2 = []
        res.data.forEach(item=>{
          if(item.type==1) {
            arr2.push(item)
          } else {
            arr1.push(item)
          }
        })
        this.roleResourceList = arr1
        this.roleResourceList2 = arr2
        if(!this.isCopy) {
          let cloneArr1 =  JSON.parse(JSON.stringify(arr1))
          let cloneArr2 =  JSON.parse(JSON.stringify(arr1))
          this.cacheRoleResourceKeys = cloneArr1.map((item) => item.resId)
          this.cacheRoleResourceKeys2 = cloneArr2.map((item) => item.resId)
          this.cacheRoleResourceList = JSON.parse(JSON.stringify(arr1))
          this.cacheRoleResourceList2 = JSON.parse(JSON.stringify(arr2))

        }
      } catch (e) {
        console.error(e)
      }
    },
    async getRoleDetailReq(roleId) {
      try {
        if(this.loading.isDetail) return
        this.loading.isDetail = true
        const params = {
          id: roleId,
        }
        const res = await getRoleManageDetailNew(params)
        this.getRoleResourceReq(roleId)
        const postList = []
        if(!this.isCopy) {
          res.data.postList && res.data.postList.forEach(item => {
            const obj = {
              id: item.postId,
              code: item.postCode,
              pname: item.postName
            }
            postList.push(obj)
          })
        }
        this.defaultNum = res.data.roleQuery&&res.data.roleQuery.isExtend == 1 ? 1 : 2
        this.isExtend = res.data.roleQuery&&res.data.roleQuery.isExtend
        const selectOrgList = []
        res.data.unitList && res.data.unitList.forEach(item => {
          const obj = {
            id: item.orgId,
            pName: item.orgName,
            name: item.orgName
          }
          selectOrgList.push(obj)
        })
        this.selectOrgList = selectOrgList;
        this.unitList = selectOrgList;
        if(!this.isCopy) {
        this.selectPost = postList;
        this.formInfo = {
          ...res.data.role,
          postList: postList,
          enable: res.data.role.enable ? 1 : 0
         }
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading.isDetail = false
      }
    },
    async getBusinessCodeReq() {
      try {
        const res = await getBusinessCode()
        this.businesscodeList = res.data || []
      } catch (e) {
        console.error(e)
      }
    },
    handleTabClick(key) {
      this.activeKey = key
    },
    handleClose() {
      // this.$close()
      this.$router.replace("/systemManage/menuPermissions/systemRoleManage")
    },
   async submit() {
      this.$emit("setLoading", true)
      this.loading.isSubmit = true
      const params = {
        ...this.formInfo,
        enable: !!this.formInfo.enable
      }
      // 新增时需要传domainId
      if(!this.formInfo.id && this.domainList.length) {
        params.domainId = this.domainList[0].id
      }
      try {
        const post = [];
        const selectedList = this.$refs.authTable.getSelectedList()
        const selectedList2 = this.$refs.authTableBuss.getSelectedList()
        let postAllName = []
        this.formInfo.postList.forEach(item=>{
          const obj = {
            "postCode": item.code,
            "postId": item.id,
            "postName": item.pname,
          }
          postAllName.push(item.pname)
          post.push(obj)
        })
        const unitList = []
        this.unitList.forEach(item=>{
          const obj = {
            orgId: item.id,
            roleId: this.roleId
          }
          unitList.push(obj)
        })
        let roleResourceKeys = this.roleResourceKeys
        let roleResourceKeys2 = this.roleResourceKeys2
        let roleResourceList = this.roleResourceList
        let roleResourceList2 = this.roleResourceList2
        if(this.isCopy) {
          roleResourceKeys = this.cacheRoleResourceKeys
          roleResourceKeys2 = this.cacheRoleResourceKeys2
          roleResourceList = this.cacheRoleResourceList
          roleResourceList2 = this.cacheRoleResourceList2
        }
        // 移除的资源项列表
        const removeList = roleResourceList
                .filter((item) => {
                  return !selectedList.find((innerItem) => innerItem.id === item.resId)
                })
                .map((item) => {
                  return {
                    roleId: this.formInfo.id,
                    resType: item.res_type,
                    resId: item.resId,
                    flag: true,
                    type: 0
                  }
                })
        // 新增的资源项列表
        const addList = selectedList
                .filter((item) => {
                  return !roleResourceKeys.includes(item.id)
                })
                .map((item) => {
                  return {
                    roleId: this.formInfo.id,
                    resType: item.data.res_type,
                    resId: item.id,
                    flag: false,
                    type: 0
                  }
                })
        // 移除的资源项列表
        const removeList2 =
                roleResourceList2
                        .filter((item) => {
                          return !selectedList2.find((innerItem) => innerItem.id === item.resId)
                        })
                        .map((item) => {
                          return {
                            roleId: this.formInfo.id,
                            resType: item.res_type,
                            resId: item.resId,
                            flag: true,
                            type: 1
                          }
                        })
        // 新增的资源项列表
        const addList2 = selectedList2
                .filter((item) => {
                  return !roleResourceKeys2.includes(item.id)
                })
                .map((item) => {
                  return {
                    roleId: this.formInfo.id,
                    resType: item.data.res_type,
                    resId: item.id,
                    flag: false,
                    type: 1
                  }
                })
        const dara = {
          postAllName: postAllName.join("，"),
          role: params,
          postList: post,
          links: [
            ...removeList,...addList,
            ...removeList2,...addList2
          ],
          roleQuery: {
            "isAllMenu": 0,
            "isExtend": this.isExtend,
            "roleId": this.formInfo.id
          },
          unitList: unitList
        }
        console.log(dara, 'dara')

        const res = await addRole(dara)
        if (res.code === '0') {
          this.$message.success('提交成功')
          if(this.isDialog) {
            this.$emit('updateList')
            return
          }
          this.handleClose()
        } else {
          this.$message.error(res.data.message || '提交失败')
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading.isSubmit = false
      }
    },
     handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if(valid) {
          this.submit()
        }else  {
          this.$message.warning("请填写完所有必填项信息")
          return  false
        }
      })
    },
  },
}
</script>

<style lang="less" scoped>
  .pos {
    min-width: 100px;
    display: inline-block;
    text-align: center;
    box-sizing: border-box;
    padding-right: 20px;
    padding-left: 10px;
    border: 1px solid #d9d9d9;
    height: 28px;
    line-height: 28px;
    font-size: 14px;
    position: relative;
    border-radius: 14px;
    margin-right: 10px;
  }
  .close {
      position: absolute;
    right: 5px;
    top: 0;
    cursor: pointer;
  }
.UpdateSystemRoleManage-container {
  .btns-wrapper {
    padding-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  .tool-btns {
    position: absolute;
    right: 0;
    top: 0;
  }

}
  .hid /deep/ .breadcrumb-wrapper {
    display: none;
  }
  .hid {
    /deep/ .ant-card {
      box-shadow: none;
    }
    /deep/ .ant-card-body {
      padding: 0;
    }
    /deep/ .ant-card-bordered {
      border: 0;
    }
  }
</style>
